package org.jiaplee.action;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.jiaplee.beans.Image;
import org.jiaplee.service.ImageService;

import com.opensymphony.xwork2.ActionSupport;

public class ImageAction extends ActionSupport {
	private String contentType;
	private File upload;
	private String fileName;
	private String caption;

	private ImageService imageService;

	private int serializable;

	public int getSerializable() {
		return serializable;
	}

	public void setSerializable(int serializable) {
		this.serializable = serializable;
	}

	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public String getUploadFileName() {
		return fileName;
	}

	public void setUploadFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getUploadContentType() {
		return contentType;
	}

	public void setUploadContentType(String contentType) {
		this.contentType = contentType;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getCaption() {
		return caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}

	@Override
	public String execute() {
		String fileType=this.fileName.substring(this.fileName.lastIndexOf("."));
		String uuid =UUID.randomUUID().toString();
		String path = ServletActionContext.getServletContext().getRealPath("/upload/");
	
		File pathfile = new File(path);
		if(false == pathfile.exists()){
			pathfile.mkdir();
		} 
		
		System.out.println(this.fileName);
		try {
			FileUtils.copyFile(upload, new File(pathfile,uuid+fileType));
		} catch (IOException e) {
			e.printStackTrace();
		}
		String filepath =path+File.separator+uuid+fileType;
		System.out.println(filepath);
		System.out.println(path);
		System.out.println(uuid);
		System.out.println(fileType);
		
		Image i = new Image();
		i.setId(fileName.hashCode());
		i.setFileName(fileName);
		i.setFilePath(filepath);
		i.setCaption(caption);
		i.setUuid(uuid+fileType);
		this.serializable = Integer.parseInt(imageService.save(i).toString());
		System.out.println((Integer) serializable);
		return SUCCESS;
	}
}
